﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

namespace Sample.Controllers
{
    public class ConvertHtml2PdfController : Controller
    {
        //
        // GET: /ConvertHtml2Pdf/

        public FileStreamResult Index()
        {
            // Create a Document object
            var document = new Document(PageSize.A4, 50, 50, 25, 25);

            // Create a new PdfWrite object, writing the output to a MemoryStream
            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, output).CloseStream = false;

            // Open the Document for writing
            document.Open();

            // Read in the contents of the Receipt.htm HTML template file
            string contents = System.IO.File.ReadAllText(Server.MapPath("~/HTMLTemplate/Receipt.htm"));

            // Replace the placeholders with the user-specified text
            contents = contents.Replace("[ORDERID]", "100101001");
            contents = contents.Replace("[TOTALPRICE]", Convert.ToDecimal("33.343").ToString("c"));
            contents = contents.Replace("[ORDERDATE]", DateTime.Now.ToShortDateString());

            var itemsTable = @"<table><tr><th style=""font-weight: bold"">Item #</th><th style=""font-weight: bold"">Item Name</th><th style=""font-weight: bold"">Qty</th></tr>";
            itemsTable += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
                                               "hello", "world", "thanks");

            itemsTable += string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>",
                                               "hello", "world", "thanks");
            itemsTable += "</table>";

            contents = contents.Replace("[ITEMS]", itemsTable);


            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);
            foreach (var htmlElement in parsedHtmlElements)
                document.Add(htmlElement as IElement);



            // You can add additional elements to the document. Let's add an image in the upper right corner
            //var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/4guysfromrolla.gif"));
            //logo.SetAbsolutePosition(440, 800);
            //document.Add(logo);

            //document.Close();

            document.Close();

            byte[] byteInfo = output.ToArray();
            output.Write(byteInfo, 0, byteInfo.Length);
            output.Position = 0;

            return new FileStreamResult(output, "application/pdf");
        }

    }
}
